﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace CopyIt
{
    class ExListBox : ListBox
    {
        private bool hasAllItem = false;

        protected override void OnDrawItem(DrawItemEventArgs e)
        {
            // Set the DrawMode property to draw fixed sized items.
            // Draw the background of the ListBox control for each item.
            e.DrawBackground();
            // Define the default color of the brush as black.
            Brush myBrush = Brushes.MidnightBlue;

            // Draw the current item text based on the current Font and the custom brush settings.
            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Center;
            sf.LineAlignment = StringAlignment.Center;
            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
            {
                e.Graphics.FillRectangle(Brushes.CornflowerBlue, e.Bounds);
            }
            //else
            //{
            //    // Otherwise, draw the rectangle filled in beige.
            //    e.Graphics.FillRectangle(, e.Bounds);
            //}

            if (e != null && e.Index >= 0 && !this.DesignMode)
                e.Graphics.DrawString(Items[e.Index].ToString(), e.Font, myBrush, e.Bounds, sf);
            // If the ListBox has focus, draw a focus rectangle around the selected item.
            e.DrawFocusRectangle();
            base.OnDrawItem(e);
        }

        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);
            Invalidate();
        }

        public int AddNewItem(string text)
        {
            int items = Items.Count - (hasAllItem ? 1 : 0);
            for (int t = 0; t < items; t++)
            {
                if (string.Compare(Items[t] as string, text) > 0)
                {
                    Items.Insert(t, text);
                    AddAllItem();
                    return t;
                }
            }
            Items.Insert(items, text);
            AddAllItem();
            return items;
        }

        public int DeleteItem(int pos)
        {
            Items.RemoveAt(pos);
            if (Items.Count == 1)
            {
                Items.Clear();
                hasAllItem = false;
                pos = -1;
            }
            else
                SelectedIndex = (pos > 0) ? pos - 1 : pos;

            return pos;
        }

        public void AddAllItem()
        {
            if (hasAllItem) return;
            Items.Add("Tutti gli abbinamenti");
            hasAllItem = true;
        }
    }
}
